package com.atguigu.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.auth.feign.MemberFeignService;

import com.atguigu.common.to.SocialUserTo;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * description: OAuth2Controller
 * date: 2022/12/10 14:47
 * author: MR.孙
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;


    /**
     * 社交登录回调
     * @param code
     * @return
     */
    @GetMapping("/oauth2.0/gitee/success")
    public String authorize(@RequestParam("code") String code, HttpSession session) throws Exception {
        //通过gitee授权后，拦截请求进入此方法进行处理逻辑

        HashMap<String, String> map = new HashMap<>(5);
        map.put("grant_type", "authorization_code");
        map.put("client_id", "6abf6c6baa6ed9aeebda00287deffec5dfaf2c13bbfc53d6d09977c343e21941");
        map.put("client_secret", "a216b0d6124e6ada5abffd0271a7395ec7a92338dbc706c1080142144e73f952");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("code", code);


        //根据code换取access_token【发送请求方式Post】
        HttpResponse post = HttpUtils.doPost("https://gitee.com",
                "/oauth/token",
                "post",
                new HashMap<>(),
                map,
                new HashMap<>());

        //处理返回结果
        if (post.getStatusLine().getStatusCode() ==200) {
            //获取access_token
            String json = EntityUtils.toString(post.getEntity());
            SocialUserTo socialUserTo = JSON.parseObject(json, new TypeReference<SocialUserTo>() {
            });
            System.out.println(socialUserTo);

            if (socialUserTo !=null && StringUtils.isNotEmpty(socialUserTo.getAccess_token())) {

                Map<String,String> queryAccessToken = new HashMap<>();
                queryAccessToken.put("access_token", socialUserTo.getAccess_token());

                Map<String,String> queryHeader = new HashMap<>();
                queryHeader.put("Content-Type","application/json;charset=UTF-8");

                //发送请求
                //https://gitee.com/api/v5/user?access_token={access_token}
                HttpResponse response = HttpUtils.doGet("https://gitee.com",
                        "/api/v5/user",
                        "get",
                        queryHeader,
                        queryAccessToken
                );

                if (response.getStatusLine().getStatusCode()==200){
                    //请求成功
                    String jsonString = EntityUtils.toString(response.getEntity());
                    SocialUserTo to = JSON.parseObject(jsonString, new TypeReference<SocialUserTo>() {
                    });

                    //获取第三方应用的用户id
                    to.setAccess_token(socialUserTo.getAccess_token());
                    to.setExpires_in(socialUserTo.getExpires_in());



                    // ===============远程调用=================
                    R login = memberFeignService.oauthLogin(to);
                    if (login.getCode()==0) {
                        //登录成功
                        MemberResponseVo responseVovo = login.getData("data", new TypeReference<MemberResponseVo>() {
                        });
                        log.info("登录成功, 用户信息:{}", responseVovo.toString());
                        //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                        //以后浏览器访问哪个网站就会带上这个网站的cookie
                        //子域之间: gulimall.com    auth.gulimall.com   order.gulimall.com
                        //发卡的时候(指定域名为父域名,即使是子域系统发的卡，也能让父域直接使用)
                        //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                        //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                        session.setAttribute("loginUser", responseVovo);

                        return "redirect:http://gulimall.com";
                    } else {
                        return "redirect:http://auth.gulimall.com/login.html";
                    }

                }
            }



            //知道了哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户

        }else {
            //授权失败
            return "redirect:http://auth.gulimall.com/login.html";
        }

        return "http://gulimall.com";
    }

}
